//
//  UserAccount.swift
//  MQLWeibo
//
//  Created by MQL-IT on 2016/11/23.
//  Copyright © 2016年 MQL-IT. All rights reserved.
//

import UIKit

private let accountFile: NSString = "userAccount.json"
/// 用户帐户信息
class UserAccount: NSObject {
    /// 访问令牌
    var access_token: String?
    /// 用户代号
    var uid: String?
    /// 过期日期,单位秒,开发者5年,使用者3年
    var expires_in: TimeInterval = 0.0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: Date?
    
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        //从磁盘加载保存的文件 -> 字典
        //1.取文件,加载磁盘文件到二进制数据,如果失败直接返回
        guard  let path = accountFile.cz_appendDocumentDir(),
               let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String : AnyObject] else {
                return
        }
       
        // 2.使用字典设置属性值
        yy_modelSet(with: dict ?? [:])
        
        printLog(message: self.description);
        
        // 3.判断token是否过期
        
        
        if expiresDate?.compare(Date()) != .orderedDescending {
            printLog(message: "帐户过期")
            // 清空token
            access_token = nil
            uid = nil
            // 删除帐户文件
            try? FileManager.default.removeItem(atPath: path)
        }
        
        
    }
    /**
     数据存储的几种方式
     1.偏好设置(小)
     2.沙盒:  归档/plist/json
     3.数据库(FMDB/coreData)
     4.钥匙串访问(小/自动加密 - 需要使用框架SSKeyChain)
     */
    
     func saveAccount() {
        // 模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        //删除expires_in
        dict.removeValue(forKey: "expires_in")
        // 字典序列化 data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let fileName = accountFile.cz_appendDocumentDir() else {
                return
        }
        // 写入磁盘
        (data as NSData).write(toFile: fileName, atomically: true)
        printLog(message: "保存成功\(fileName)")
    }
    
}
